<!--供应商对账单-->
<template>
  <div class="supplier-statement-container">
    <!-- 筛选区域 -->
    <div class="controls-section">
      <button class="btn-new" @click="openCreate">新建</button>
      <div class="filters">
        <div class="filter-item">
          <label>对账单号</label>
          <input type="text" v-model="query.reconciliationNo" placeholder="请输入对账单号">
        </div>
        <div class="filter-item">
          <label>对账状态</label>
          <select v-model.number="query.status">
            <option :value="''">全部</option>
            <option :value="0">待对账</option>
            <option :value="1">已对账</option>
          </select>
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="fetchList">搜索</button>
        <button class="btn-secondary" @click="resetQuery">重置</button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>对账单号</th>
            <th>对账状态</th>
            <th>供应商</th>
            <th>账单创建日</th>
            <th>对账起始/终止日</th>
            <th>账单周期</th>
            <th>本期应付</th>
            <th>本期待付</th>
            <th>本期已付</th>
            <th>财务人员</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in statements" :key="index">
            <td><input type="checkbox" v-model="item.selected"></td>
            <td class="link-style" @click="openDetail(item)">{{ item.reconciliationNo }}</td>
            <td><span :class="statusClass(item.status)">{{ statusText(item.status) }}</span></td>
            <td class="link-style">{{ item.supplierName }}</td>
            <td>{{ item.createTime }}</td>
            <td>{{ item.reconciliationPeriod || '-' }}</td>
            <td>{{ item.reconciliationPeriod || '-' }}</td>
            <td>{{ formatNumber(item.totalPurchase) }}</td>
            <td>{{ formatNumber(calcPending(item)) }}</td>
            <td>{{ formatNumber(item.totalPayment) }}</td>
            <td>{{ item.financeStaffName || '-' }}</td>
            <td>{{ item.remarks }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected">
        <label>全选</label>
        <button class="btn-secondary">导出</button>
      </div>
      <div class="pagination">
        <button @click="changePage(page-1)" :disabled="page<=1">&lt;</button>
        <button class="active">{{ page }}</button>
        <button @click="changePage(page+1)" :disabled="page>=pages">&gt;</button>
        <select v-model.number="pageSize" @change="changePageSize">
          <option :value="5">5条/页</option>
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>

        </select>
      </div>
    </div>

    <!-- 新建对账单 - 弹窗（统一样式） -->
    <div v-if="showCreate" class="create-modal">
      <div class="modal-overlay" @click="onCancelCreate"></div>
      <div class="modal-content">
        <div class="modal-header">
          <span class="modal-title">新建供应商对账单</span>
          <button class="close-btn" @click="onCancelCreate">×</button>
        </div>
        <div class="modal-body">
          <div class="form-row">
            <div class="form-group">
              <label class="required">供应商</label>
              <select v-model.number="createForm.supplierId">
                <option :value="null" disabled>请选择供应商</option>
                <option v-for="s in supplierOptions" :key="s.id" :value="s.id">{{ s.supplierName }} {{ s.supplierCode }}</option>
              </select>
            </div>
            <div class="form-group">
              <label class="required">财务人员</label>
              <select v-model.number="createForm.uId">
                <option :value="null" disabled>请选择财务人员</option>
                <option v-for="u in userOptions" :key="u.userId" :value="u.userId">{{ u.realName }}</option>
              </select>
            </div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label>对账周期</label>
              <input v-model="createForm.reconciliationPeriod" placeholder="例如 2025-06" />
            </div>
            <div class="form-group">
              <label>对账状态</label>
              <select v-model.number="createForm.status">
                <option :value="0">待对账</option>
                <option :value="1">已对账</option>
              </select>
            </div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label>本期应付</label>
              <input v-model.number="createForm.totalPurchase" type="number" step="0.01" placeholder="0.00" />
            </div>
            <div class="form-group">
              <label>本期收货额</label>
              <input v-model.number="createForm.totalReceipt" type="number" step="0.01" placeholder="0.00" />
            </div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label>本期已付</label>
              <input v-model.number="createForm.totalPayment" type="number" step="0.01" placeholder="0.00" />
            </div>
            <div class="form-group">
              <label>备注</label>
              <input v-model="createForm.remarks" placeholder="备注(可选)" />
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn-cancel" @click="onCancelCreate">取消</button>
          <button class="btn-save" @click="submitCreate">确定</button>
        </div>
      </div>
    </div>

    <!-- 查看详情 - 右侧抽屉 -->
    <div v-if="showDetail" class="drawer-mask" @click="showDetail=false">
      <div class="drawer" @click.stop>
        <div class="drawer-header">
          <span>对账单详情</span>
          <button class="modal-close" @click="showDetail=false">×</button>
        </div>
        <div class="drawer-body" v-if="detailData">
          <!-- 基本信息 -->
          <div class="detail-section">
            <h3>基本信息</h3>
            <div class="detail-form">
              <div class="form-field">
                <label>对账单号</label>
                <input type="text" :value="detailData.reconciliationNo" readonly>
              </div>
              <div class="form-field">
                <label>对账状态</label>
                <input type="text" :value="statusText(detailData.status)" readonly>
              </div>
              <div class="form-field">
                <label>供应商</label>
                <input type="text" :value="detailData.supplierName || detailData.supplierId" readonly>
              </div>
              <div class="form-field">
                <label>创建时间</label>
                <input type="text" :value="detailData.createTime" readonly>
              </div>
            </div>
          </div>

          <!-- 对账信息 -->
          <div class="detail-section">
            <h3>对账信息</h3>
            <div class="detail-form">
              <div class="form-field">
                <label>对账周期</label>
                <input type="text" :value="detailData.reconciliationPeriod || '-'" readonly>
              </div>
              <div class="form-field">
                <label>财务人员</label>
                <input type="text" :value="detailData.financeStaffName || '-'" readonly>
              </div>
              <div class="form-field">
                <label>本期应付</label>
                <input type="text" :value="formatNumber(detailData.totalPurchase)" readonly>
              </div>
              <div class="form-field">
                <label>本期已付</label>
                <input type="text" :value="formatNumber(detailData.totalPayment)" readonly>
              </div>
              <div class="form-field" style="grid-column: span 2">
                <label>备注</label>
                <input type="text" :value="detailData.remarks || '-'" readonly>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { recoPage, recoCreate, recoDetail } from '@/api/finance/supplierReconciliation'
import { listActiveSuppliers, listActiveUsers } from '@/api/finance/supplierCommon'
export default {
  name: 'SupplierStatement',
  data() {
    return {
      statements: [],
      page: 1,
      pageSize: 5,
      pages: 1,
      total: 0,
      query: { reconciliationNo: '', status: null, startDate: '', endDate: '' },
      showCreate: false,
      createForm: { supplierId: null, reconciliationPeriod: '', remarks: '' },
      showDetail: false,
      detailData: null,
      supplierOptions: [],
      userOptions: []
    };
  },
  computed: {
    allSelected: {
      get() {
        return this.statements.length > 0 && this.statements.every(item => item.selected);
      },
      set(value) {
        this.statements.forEach(item => {
          item.selected = value;
        });
      }
    }
  },
  mounted() {
    this.fetchList();
    this.loadOptions();
  },
  methods: {
    resetCreateForm() {
      this.createForm = {
        supplierId: null,
        uId: null,
        reconciliationPeriod: '',
        totalPurchase: undefined,
        totalReceipt: undefined,
        totalPayment: undefined,
        status: 0,
        remarks: ''
      }
    },
    openCreate() {
      this.resetCreateForm()
      this.showCreate = true
    },
    onCancelCreate() {
      this.resetCreateForm()
      this.showCreate = false
    },
    formatNumber(val) {
      const num = Number(val || 0)
      return num.toFixed(2)
    },
    async loadOptions() {
      // 供应商
      try {
        const sRes = await listActiveSuppliers({ pageSize: 200 });
        const payload = sRes?.data || {};
        const data = payload.data || payload;
        this.supplierOptions = (data.records || []).map(x => ({ id: x.id, supplierName: x.supplierName, supplierCode: x.supplierCode }));
      } catch(e) { this.supplierOptions = []; }
      // 财务人员
      try {
        const uRes = await listActiveUsers();
        const list = (uRes?.data?.data) || (uRes?.data) || [];
        this.userOptions = Array.isArray(list) ? list : [];
      } catch(e) { this.userOptions = []; }
    },
    calcPending(row) {
      const total = Number(row?.totalPurchase || 0)
      const paid = Number(row?.totalPayment || 0)
      const pending = total - paid
      return pending < 0 ? 0 : pending
    },
    statusClass(status) {
      if (status === 0) return 'status-pending';
      if (status === 1) return 'status-completed';
      return '';
    },
    statusText(status) {
      if (status === 0) return '待对账';
      if (status === 1) return '已对账';
      return '-';
    },
    async fetchList() {
      const req = { pageNum: this.page, pageSize: this.pageSize, ...this.query };
      if (req.status === '') delete req.status;
      const res = await recoPage(req);
      const payload = res?.data || {};
      const data = payload.data || payload;
      const records = data.records || [];
      this.total = data.total || 0;
      this.pages = data.pages || Math.ceil(this.total / this.pageSize) || 1;
      this.statements = records.map(it => ({ ...it, selected: false }));
    },
    resetQuery() {
      this.query = { reconciliationNo: '', status: null, startDate: '', endDate: '' };
      this.page = 1;
      this.fetchList();
    },
    changePage(p) {
      if (p < 1 || p > this.pages) return;
      this.page = p;
      this.fetchList();
    },
    changePageSize() {
      this.page = 1;
      this.fetchList();
    },
    async submitCreate() {
      // 简单必填校验，避免后端 500（u_id/supplier_id 不能为空）
      if (!this.createForm.supplierId) {
        return this.$message && this.$message.error('请选择供应商');
      }
      if (!this.createForm.uId) {
        return this.$message && this.$message.error('请选择财务人员');
      }
      const payload = {
        ...this.createForm,
        supplierId: Number(this.createForm.supplierId),
        uId: Number(this.createForm.uId)
      }
      await recoCreate(payload);
      if (this.$message) this.$message.success('新建成功');
      this.onCancelCreate();
      this.fetchList();
    },
    async openDetail(row) {
      const res = await recoDetail(row.id);
      const payload = res?.data || {};
      this.detailData = payload.data || payload;
      this.showDetail = true;
    }
  }
}
</script>

<style scoped>
/* 统一弹窗样式（与待对账供应商新建一致） */
.create-modal { position: fixed; inset: 0; z-index: 1000; display: flex; align-items: center; justify-content: center; }
.modal-overlay { position: absolute; inset: 0; background: rgba(0,0,0,0.5); }
.modal-content { position: relative; background: #fff; border-radius: 4px; width: 640px; max-width: 95vw; max-height: 90vh; overflow: auto; box-shadow: 0 4px 20px rgba(0,0,0,0.15); }
.modal-header { background: lightskyblue; color: #fff; padding: 16px 20px; border-radius: 4px 4px 0 0; display:flex; align-items:center; justify-content:space-between; }
.modal-title { font-size: 16px; font-weight: 600; }
.close-btn { background: transparent; border: 0; color:#fff; font-size:20px; cursor:pointer; }
.modal-body { padding: 20px; }
.form-row { display:flex; gap:16px; margin-bottom:16px; }
.form-group { flex:1; display:flex; flex-direction:column; }
.form-group label { font-size:14px; color:#333; margin-bottom:6px; font-weight:500; }
.form-group label.required { color:#f56c6c; }
.form-group label.required::after { content:' *'; color:#f56c6c; }
.form-group input, .form-group select, .form-group textarea { padding:8px 12px; border:1px solid #d9d9d9; border-radius:4px; font-size:14px; }
.form-group input:focus, .form-group select:focus, .form-group textarea:focus { outline:none; border-color:#1890ff; box-shadow:0 0 0 2px rgba(24,144,255,0.1); }
.modal-footer { padding: 16px 20px; border-top:1px solid #f0f0f0; display:flex; justify-content:flex-end; gap:12px; }
.btn-cancel { padding:8px 20px; border:1px solid #d9d9d9; background:#fff; color:#333; border-radius:4px; cursor:pointer; }
.btn-save { padding:8px 20px; border:0; background:#1890ff; color:#fff; border-radius:4px; cursor:pointer; }

/* 右侧抽屉 */
.drawer-mask { position: fixed; inset:0; background: rgba(0,0,0,0.35); display:flex; justify-content:flex-end; align-items:stretch; z-index:1000; }
.drawer { width: 520px; max-width:85vw; height:100%; background:#fff; box-shadow:-2px 0 12px rgba(0,0,0,0.1); display:flex; flex-direction:column; animation: slideInRight 0.25s ease-out; }
.drawer-header { display:flex; justify-content:space-between; align-items:center; padding:12px 16px; border-bottom:1px solid #ebeef5; background:#ffffff; color:#303133; }
.drawer-header span { color:#303133; }
.modal-close { color:#909399; }
.modal-close:hover { background-color: rgba(0,0,0,0.05); color:#606266; }
.drawer-body { padding:16px; overflow:auto; }
.detail-section { margin-bottom: 24px; }
.detail-section h3 { margin: 0 0 12px; padding-bottom: 8px; border-bottom: 2px solid #409eff; font-size: 16px; font-weight: 600; color:#303133; }
.detail-form { display:grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.form-field { display:flex; flex-direction:column; gap:8px; }
.form-field label { font-weight:500; color:#606266; font-size:14px; }
.form-field input { padding:10px 12px; border:1px solid #dcdfe6; border-radius:4px; background-color:#f5f7fa; color:#606266; }
.form-field input:read-only { background-color:#f5f7fa; cursor:not-allowed; }
@keyframes slideInRight { from { transform: translateX(100%);} to { transform: translateX(0);} }
.form-row { display:flex; align-items:center; gap:12px; margin-bottom:12px; }
.form-row label { width: 110px; color: #606266; text-align: right; }
.form-row input, .form-row select { flex: 1; padding: 8px; border:1px solid #dcdfe6; border-radius:4px; }
.detail-grid { display:grid; grid-template-columns: 1fr 1fr; gap:10px 16px; }
.supplier-statement-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.controls-section {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.btn-new {
    background-color: #409eff;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
}

.filters {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  white-space: nowrap;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 150px;
}

.actions {
  margin-left: auto;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

.link-style {
    color: #409eff;
    cursor: pointer;
}

.status-pending { color: #67c23a; }
.status-partial { color: #e6a23c; }
.status-completed { color: #f56c6c; }

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>
